
package com.example.websocketserver.controller;

import com.alibaba.fastjson.JSON;
import com.example.websocketserver.configuration.WebsocketPushService;
import com.example.websocketserver.pojo.WebSocketModuleEnum;
import com.example.websocketserver.pojo.WebsocketRealMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Controller
@RequiredArgsConstructor
public class WebsocketController {

    private final WebsocketPushService pushService;

    /**
     * 广播消息【示例】
     *
     * @param message 消息内容
     * @param
     */
    @GetMapping("push")
    @ResponseBody
    public String push(String message, String module, String uniqueKey) throws JsonProcessingException {
        WebsocketRealMessage param = new WebsocketRealMessage();
        param.setModule(module);
        param.setContent(message);
        WebSocketModuleEnum topic = WebSocketModuleEnum.getByModule(module);
        this.pushService.push2Topic(topic.getTopicName(uniqueKey), param);
        return "ok";
    }

    /**
     * 后台主动推送点对点消息【示例】
     */
    @RequestMapping(value = "/user/send")
    @ResponseBody
    public void templateTest(String userId) throws JsonProcessingException {
        log.info("推送给特定用户:{}", userId);
        WebsocketRealMessage message = new WebsocketRealMessage();
        message.setContent("特定用户[{" + userId + "}]数据");
        // TODO 待做成枚举
        this.pushService.push2User(userId, "/queue/point", message);
    }

    /**
     * 动态订阅
     */
    @MessageMapping("/topic/msg.announcement.{enterpriseId}")
    public void topicAnnouncementMsg(@DestinationVariable("enterpriseId") String enterpriseId, Principal principal) {
        log.info("MsgCenterWebSocketController::topicAnnouncementMsg::enterpriseId = [{}], principal = [{}]", enterpriseId, principal);
    }

    /**
     * 接收前端发送的消息[send stomp请求，非http]
     */
    @MessageMapping("/topic/device.A001001")
    public void pushMessage(WebsocketRealMessage clientMessage) {
        log.info("接收stomp消息:{}", JSON.toJSONString(clientMessage));
    }

}